package com.ksl.kinglockguard.activity;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.Toast;

import com.ksl.kinglockguard.R;
import com.ksl.kinglockguard.activity.base.AbstractActivity;
import com.ksl.kinglockguard.data.Constants;
import com.ksl.kinglockguard.data.SharePreferenceSdkData;
import com.ksl.kinglockguard.data.UserCountHabit;
import com.ksl.kinglockguard.domain.BannerNews;
import com.ksl.kinglockguard.domain.H5News;
import com.ksl.kinglockguard.domain.MainNews;
import com.ksl.kinglockguard.domain.base.BaseNews;
import com.ksl.kinglockguard.game._interface.GameInterface;
import com.ksl.kinglockguard.game._interface.JSGameInterface;
import com.ksl.kinglockguard.game._interface.GameInterface.GameExitListener;
import com.ksl.kinglockguard.network.MyDownloadManager;
import com.ksl.kinglockguard.widget.common.LoadFailedView;
import com.ksl.kinglockguard.widget.common.MyTitleView;
import com.ksl.kinglockguard.widget.common.MyTitleView.MenuImageResourceListener;
import com.lsk.open.core.MyLog;
import com.lsk.open.core.net.NetHeadUtils;

@SuppressLint("JavascriptInterface")
public class DetailPageActivity extends AbstractActivity implements
		MenuImageResourceListener,OnClickListener,GameExitListener {
//	public static final String FROM_HOME_LIST = "main";
//	public static final String FROM_SCREEN = "screen";
//	public static final String FROM_FOCUS = "focus";
	
	/**webview加载超时时间**/
	private static final int TIMEOUT = 60 * 1000;
	private static final int TIMEOUT_ERROR = 9527;

	
	/**titlebar的管理**/
	private MyTitleView myTitleView;
	/**内容详情**/
	private WebView webview;
	/**刷新**/
	private ImageView refreshImg;
	/**分享**/
	private ImageView shareImg;
	/**详情的整体相关**/
	private RelativeLayout curView;
	private ViewGroup lay_layout;
	private RelativeLayout lay_detail_container;
	/**webview的加载进度**/
	private ProgressBar progressBar;
	/**加载失败或者没有网络的占位图**/
	private LoadFailedView lay_no_net;

	/**webview的加载超时**/
	private Timer mTimer;
	private TimerTask mTimerTask;
	
	private int articleId;
	private int lastArticleId;
	private String articleUrl;
	private String articleTitle;
	private String from;
	private boolean fromScreen = false;
	private boolean fromFocus = false;
	private boolean fromList = false;
	private boolean fromGameList = false;
	private boolean fromShortcut = false;
	
	private boolean backKeyPressed = false;
	private boolean homeIconPressed = false;
	private boolean isNetworkChanged = false;
	
	private MainNews mCommonNews;
	private BannerNews mFocusNews;
	private H5News mH5News;
	private BaseNews mNews;
	private boolean isLoaded =false;
	//H5游戏计费相关
	GameInterface gameInterface;
	
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case TIMEOUT_ERROR:
				if (webview != null && webview.getProgress() < 100) {
					Toast.makeText(getApplicationContext(), getApplicationContext().getResources().getString(R.string.network_env_bad),
							Toast.LENGTH_SHORT).show();
					resetTimer();
				}
				break;

			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		MyLog.i("jyh1", "~~~~~~~~~~back from home key and onCreate onCreate~~~~~~~~~");
		setContentView(R.layout.lock_detail_page_activity);
		initData(getIntent());
		initView();
		initListener();
		//这个里面需要一个js object
		gameInterface = new JSGameInterface(this, webview);
	}
	
	private void handleDirection() {
    	String direction = mH5News.getPlay_game_screen_direction();
    	if(direction == null || "".equals(direction)) {
    		return ;
    	}
    	if (H5News.GAME_SCREEN_DIRECTION_HORIZON.equalsIgnoreCase(direction)) {
    		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else if(H5News.GAME_SCREEN_DIRECTION_VERTICAL.equalsIgnoreCase(direction)){
        	getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        			WindowManager.LayoutParams.FLAG_FULLSCREEN);
        	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
        	setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
	}

	private void initData(Intent intent) {
		if(intent==null){
    		finish();
    		return;
    	}
		dismissPopup();
		from = intent.getStringExtra(Constants.FROM);
		if(Constants.FROM_SHORT_CUT.equals(from)){//从快捷方式进入
			fromShortcut = true;
			articleUrl = (String) intent.getStringExtra("gameUrl");
			articleTitle = (String) intent.getStringExtra("gameName");
			articleId = (int) intent.getIntExtra("gameId",-1);
			if(articleUrl != null && articleTitle != null && articleId != -1){
				UserCountHabit.setUserCount(DetailPageActivity.this,UserCountHabit.H5_CLICK_SHORTCUT_NUM+articleId);
				mH5News = new H5News();
				mH5News.setArticleUrl(articleUrl);
				mH5News.setTitle(articleTitle);
				mH5News.setId(articleId);
			}else{
				finish();
			}
			return;
		}
		mNews = (BaseNews) intent.getSerializableExtra("curNews");
		if(mNews == null){
			finish();
			return;
		}
		articleId = mNews.getId();
		articleUrl = mNews.getArticleUrl();
		articleTitle = mNews.getTitle();
		if(Constants.FROM_FOCUS.equals(from)){
			// 从首页焦点图进来
			fromFocus = true; 
			if(mNews instanceof BannerNews){
				mFocusNews = (BannerNews) mNews;
			}
			UserCountHabit.setUserCount(DetailPageActivity.this,
					UserCountHabit.DETAIL_FROM_BANNER + articleId);
		}else if(Constants.FROM_H5_PAGE.equals(from)){
			if(mNews instanceof H5News){
				mH5News = (H5News) mNews;
			}
			fromGameList = Constants.FROM_H5_PAGE.equals(from);
			UserCountHabit.setUserCount(DetailPageActivity.this, UserCountHabit.DETAIL_FROM_GAME+articleId);
		} else {
			if(mNews instanceof MainNews){
				mCommonNews = (MainNews) mNews;
			}
			
			if(Constants.FROM_SCREEN.equals(from)){
				fromScreen = true;
				UserCountHabit.setUserCount(DetailPageActivity.this, UserCountHabit.DETAIL_FROM_SCREENLOCK+articleId);
			}else if(Constants.FROM_HOME_LIST.equals(from)){
				fromList = true;
				UserCountHabit.setUserCount(DetailPageActivity.this, UserCountHabit.DETAIL_FROM_LIST+articleId);
			}
			UserCountHabit.setUserCount(DetailPageActivity.this,
					UserCountHabit.DESK_ACTID + articleId);
		}
	}

	private void reLoadPageView(BaseNews page) {
//		checkNectwork();
		articleUrl = page.getArticleUrl();
		articleTitle = page.getTitle();
		myTitleView.setTitle(articleTitle);
		// news_title.setText(articleTitle);
		progressBar.setVisibility(View.VISIBLE);
		webview.clearHistory();
		webview.loadUrl(articleUrl);
		webview.postDelayed(new Runnable() {
			@Override
			public void run() {
				if(webview != null){
					webview.clearHistory();
				}
			}
		}, 1000);
	}


	private void initView() {
		initTitleBar();
		// webview = (WebView) findViewById(R.id.webview);
		lay_layout = (ViewGroup) findViewById(R.id.lay_layout);
		refreshImg = (ImageView) findViewById(R.id.refresh_img);
		shareImg = (ImageView) findViewById(R.id.share_img);
		progressBar = (ProgressBar) findViewById(R.id.progressbar);
		lay_detail_container = (RelativeLayout) findViewById(R.id.lay_detail_container);
		curView = (RelativeLayout) View.inflate(getApplicationContext(),
				R.layout.lock_detail_view, null);
		initWebView();
		curView.addView(webview,new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
	
		if(Constants.FROM_H5_PAGE.equals(from) || (mCommonNews != null && mCommonNews.getSlide2browser() == 2)){
			lay_detail_container.addView(curView);
		} else {
			LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
			params.bottomMargin = 10;
			params.topMargin = 8;
			lay_detail_container.addView(curView,params);
		}
		
		lay_no_net = (LoadFailedView) findViewById(R.id.lay_no_net);
		if(progressBar != null)
			progressBar.setMax(100);
		if (fromScreen || fromFocus || Constants.FROM_H5_PAGE.equals(from) || fromShortcut) {
			lay_layout.setBackgroundResource(R.drawable.bg_ss);
		}
		checkNectwork();

	}
	
	private void checkNectwork(){
		if(NetHeadUtils.isNetWorking(getApplicationContext())){
				setNoNetViewVisibility(false);
		}else{
			setNoNetViewVisibility(true);
		}
		
	}

	@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
	private void initWebView() {
		webview = new WebView(this);
		webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
		
//自适应屏幕
		webview.getSettings().setLoadWithOverviewMode(true);
//设置此属性，可任意比例缩放
//		webview.getSettings().setUseWideViewPort(true);
// ---------------- 滚动相关　start --------------		
		webview.setHorizontalScrollBarEnabled(false);//水平不显示
		webview.setVerticalScrollBarEnabled(true); //垂直不显示
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
			webview.setScrollBarSize(2);
		}
//				webview.setVerticalScrollbarOverlay(true);
// ---------------- 滚动相关　end --------------
		
// ---------------- 渲染加速　start --------------
		webview.getSettings().setRenderPriority(RenderPriority.HIGH);
		//把图片加载放在最后来加载渲染
		webview.getSettings().setBlockNetworkImage(true);		
// ---------------- 渲染加速　end --------------		
// ---------------- 缓存相关　start --------------
		webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		// 开启 DOM storage API 功能 
        webview.getSettings().setDomStorageEnabled(true); 

        //开启 database storage API 功能 
        webview.getSettings().setDatabaseEnabled(true);		//默认放在“/data/data/包名/databases目录下
        //设置数据库缓存路径 
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
        	webview.getSettings().setDatabasePath("/data/data/" + getPackageName() + "/databases/");
        }                                                                                                                   
        
        //开启 Application Caches 功能 
        webview.getSettings().setAppCacheEnabled(true);
        //设置appcache最大为80M   
        webview.getSettings().setAppCacheMaxSize(1024 * 1024 * 80);
        //设置  Application Caches 缓存目录
        File cacheDir = getCacheDir();
        if(cacheDir != null ){
        	String cacheDirPath = cacheDir.getAbsolutePath(); 
        	webview.getSettings().setAppCachePath(cacheDirPath); 
        }
// ---------------- 缓存相关　end --------------    
		        
		WebSettings settings = webview.getSettings();
		settings.setJavaScriptEnabled(true);
		settings.setSupportZoom(false);
		settings.setBuiltInZoomControls(false);
		webview.addJavascriptInterface(this, "lock");
		webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
//		webview.setBackgroundColor(Color.TRANSPARENT);
		
		webview.setBackgroundColor(0);

		webview.setWebViewClient(new KingsWebViewClient());

		webview.setWebChromeClient(new ProgressWebViewClient());
	}

	@Override
	public File getCacheDir() {
		File cachePath = getExternalCachePath();
        return cachePath != null ? cachePath : super.getCacheDir();
	}
	
	private File getExternalCachePath() {
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            File extStorageAppCachePath = new File(Constants.FOLDER_WEBVIEWCACHE);
            return extStorageAppCachePath;
        }
        return null;
    }
	

	private void setNoNetViewVisibility(boolean isShow) {
		if (isShow) {
			lay_no_net.setVisibility(View.VISIBLE);
			lay_detail_container.setVisibility(View.GONE);
		} else {
			lay_no_net.setVisibility(View.GONE);
			lay_detail_container.setVisibility(View.VISIBLE);
		}
	}

	private void initTitleBar() {

		myTitleView = new MyTitleView(this, false);
		myTitleView.setMenuImageResourceListener(this);
		myTitleView.setTitle(articleTitle);
		myTitleView.setTitleGravity(Gravity.CENTER);
		myTitleView.addMenuView(4, R.drawable.btn_topbar_more_normal, new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				showPopup(v);
			}
		});
		
		if (from.equals("screen")) {
			// 这个ID是menu的标示
			myTitleView.addMenuView(3, R.drawable.btn_suop_xiangq_list_normal,
					new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							homeIconPressed = true;
							toMain();
						}
					});
		}
		if (Constants.IS_GAMECENTER) {
			myTitleView.setMenuViewVisibility(View.GONE);
		}
	}
	
	private PopupWindow popup;
	
	private void showPopup(View anchor){
		if(popup != null && popup.isShowing()){
			popup.dismiss();
		}else{
			View view = View.inflate(getApplicationContext(), R.layout.detail_more_list, null);
			view.findViewById(R.id.tv_refresh).setOnClickListener(this);
			view.findViewById(R.id.tv_browser).setOnClickListener(this);
			view.findViewById(R.id.tv_share).setOnClickListener(this);
            view.findViewById(R.id.copy_link).setOnClickListener(this);

			view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
			popup = new PopupWindow(view);
			popup.setWidth(view.getMeasuredWidth()+60);
			popup.setHeight(view.getMeasuredHeight());
			popup.setOutsideTouchable(true);
			popup.setTouchable(true);
			popup.setFocusable(true);
			popup.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup_background));
//			popup.showAsDropDown(anchor);
			popup.showAsDropDown(anchor, -(popup.getWidth()-50), 0);
		}
	}

	private void initListener() {
		lay_no_net.setOnClickListener(this);

	}

	private void refresh() {
		UserCountHabit.setUserCount(DetailPageActivity.this,
				UserCountHabit.DETAIL_REFRESH);
		
//		UserCountHabit.setUserCount(DetailPageActivity.this,
//				"test","def");//todo ydy
		
		progressBar.setVisibility(View.VISIBLE);
		if(webview != null){
			webview.clearView();
	//		webview.clearCache(true);
	//		webview.clearHistory();
			webview.reload();
		}
	}

	// Web
	private class KingsWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			try {
				if (url.contains("d=ks")) {
					MyDownloadManager.getInstance().download(
							getApplicationContext(), url.replace("&d=ks", ""));
				} else {
					Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
					it.setAction("android.intent.action.VIEW");
					startActivity(it);
				}
			} catch (Exception e) {
				if(webview != null)
					webview.loadUrl(url);
				e.printStackTrace();
			}
			return true;
		}

		@Override
		public void onPageStarted(final WebView view, String url, Bitmap favicon) {
			mTimer = new Timer();
			mTimerTask = new TimerTask() {
				@Override
				public void run() {
					mHandler.sendEmptyMessage(TIMEOUT_ERROR);

				}
			};
			mTimer.schedule(mTimerTask, TIMEOUT);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			isLoaded=true;
			MyLog.i("wmm", "onPageFinished");
			if(webview != null)
				webview.getSettings().setBlockNetworkImage(false); 
			resetTimer();
		}

		@Override
		public void onReceivedError(WebView view, int errorCode,
				String description, String failingUrl) {
			super.onReceivedError(view, errorCode, description, failingUrl);
			MyLog.i("wmm", "webview loaded error>>>" + errorCode + ">>>"
					+ description);
 		   setNoNetViewVisibility(true);
		}

	}

	private class ProgressWebViewClient extends WebChromeClient {
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			progressBar.setProgress(newProgress);
			if (newProgress == 100) {
				mHandler.postDelayed(new Runnable() {
					@Override
					public void run() {
						progressBar.setVisibility(View.GONE);
					}
				}, 200);
			}
			super.onProgressChanged(view, newProgress);
		}
	}

	@Override
	public void onPause() {// 继承自Activity
		super.onPause();
		if(!homeIconPressed && !backKeyPressed){
        	SharePreferenceSdkData.setHomeKeyState(getApplicationContext(), true);
        	MyLog.i("jyh1", "~~~~~~~~~~getHomeKeyState~~~~~~~~~"+SharePreferenceSdkData.getHomeKeyState(getApplicationContext()));
		}else{
			homeIconPressed = false;
			backKeyPressed = false;
		}
		fromList = false;
		fromFocus = false;
		fromScreen = false;
		if(webview != null)
			webview.onPause();
	}

	private void resetTimer(){
		if(mTimer != null){
			mTimer.cancel();
			mTimer.purge();
		}
		if(mTimerTask != null){
			mTimerTask.cancel();
			mTimerTask = null;
		}
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		MyLog.i("ydy", "DetailPageActivity ***onDestroy****");
		sendBroadcast(new Intent("intent.com.ksl.usercount_upload"));
		if(webview != null){
			webview.destroyDrawingCache();
			curView.removeView(webview);
			webview.destroy();
			webview = null;
		}
		if(gameInterface !=null) {
            gameInterface.onExitGame();
            gameInterface = null;
		}
		resetTimer();
	}

	@Override
	public void setMenuImageResource(ImageView menu_img, int id) {

		switch (id) {
		case 1:
			menu_img.setImageResource(R.drawable.lock_pagedown_img_click);
			break;
		case 2:
			menu_img.setImageResource(R.drawable.lock_pageup_img_click);
			break;
		case 3:
			menu_img.setImageResource(R.drawable.lock_suop_list_selector);
			break;
		case 4:
			menu_img.setImageResource(R.drawable.lock_more_list_selector);

		default:
			break;
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			goBackPreviousPage(false);
			return true;
		default:
			break;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void toMain() {
		UserCountHabit.setUserCount(DetailPageActivity.this,
				UserCountHabit.TO_MAIN);
		Intent intent = new Intent(DetailPageActivity.this,
				LockMainActivity.class);
		intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		this.finish();
	}

	@Override
	public void setImageBtnGray(ImageView menu_img, int id) {
		// TODO Auto-generated method stub
		if (id == 1)
			menu_img.setImageResource(R.drawable.btn_xiangq_next_press);
		else if (id == 2)
			menu_img.setImageResource(R.drawable.btn_xiangq_last_press);
	}

	@Override
	public void setImageBtnNormal(ImageView menu_img, int id) {
		// TODO Auto-generated method stub
		if (id == 1)
			menu_img.setImageResource(R.drawable.lock_pagedown_img_click);
		else if (id == 2)
			menu_img.setImageResource(R.drawable.lock_pageup_img_click);
	}

	/**
	 * 推荐好友
	 */
	protected void sendToFriend() {
		UserCountHabit.setUserCount(DetailPageActivity.this, UserCountHabit.DETAIL_SHARE_ID+articleId);
		Intent shareIntent = new Intent(Intent.ACTION_SEND);
		shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		shareIntent.putExtra(Intent.EXTRA_SUBJECT, "share");
		shareIntent.putExtra(Intent.EXTRA_TEXT, articleTitle + "\n "
				+ articleUrl + getApplicationContext().getResources().getString(R.string.from_onion_locker));
		shareIntent.setType("text/plain");
		shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(Intent.createChooser(shareIntent, "share"));
	}

	@Override
	protected void onResume() {
		super.onResume();
		handleDirection();
		MyLog.i("jyh1", "~~~~~~~~~~getHomeKeyState~~~~~~~~~"+SharePreferenceSdkData.getHomeKeyState(this));
		if(SharePreferenceSdkData.getHomeKeyState(this)){
			lay_layout.setBackgroundResource(R.drawable.bg_ss);
		}
		if(webview != null)
			webview.onResume();
		if (!isLoaded&&NetHeadUtils.isNetWorking(getApplicationContext())) {
			progressBar.setVisibility(View.VISIBLE);
			setNoNetViewVisibility(false);
			lay_detail_container.setVisibility(View.VISIBLE);
			if(webview != null)
				webview.loadUrl(articleUrl);
		}
	}


	@Override
	public void goBackPreviousPage(boolean parentPage) {
		MyLog.i("jyh1", "~~~~~~goBackPreviousPage（）~~~~~~~~~");
		backKeyPressed = true;
		if (webview.canGoBack()) {
			webview.goBack();
		} else if (fromScreen || isNetworkChanged) {
			Intent data = new Intent();
			setResult(LockMainActivity.BACK_FROM_DETAIL_NOANIM, data);
			this.finish();
			overridePendingTransition(0, android.R.anim.slide_out_right);
		}else if(SharePreferenceSdkData.getHomeKeyState(this)){
			SharePreferenceSdkData.setHomeKeyState(this, false);
			Intent data = new Intent();
			setResult(LockMainActivity.BACK_FROM_DETAIL_NOANIM, data);
			this.finish();
			overridePendingTransition(0, android.R.anim.slide_out_right);
		}else {
			Intent data = new Intent();
			setResult(LockMainActivity.BACK_RROM_DETAIL_PAGE, data);
			this.finish();
			overridePendingTransition(R.anim.enter_alpha, R.anim.leave_alpha);
		}
	}

	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		MyLog.i("jyh3", "~~~~~detail page activity onNewIntent~~~~");
		from = intent.getStringExtra(Constants.FROM);
		if(Constants.FROM_SHORT_CUT.equals(from)){//从快捷方式进入
			fromShortcut = true;
			articleUrl = (String) intent.getStringExtra("gameUrl");
			articleTitle = (String) intent.getStringExtra("gameName");
			articleId = (int) intent.getIntExtra("gameId",-1);
			if(articleUrl != null && articleTitle != null && articleId != -1){
				UserCountHabit.setUserCount(DetailPageActivity.this,UserCountHabit.H5_CLICK_SHORTCUT_NUM+articleId);
				mH5News = new H5News();
				mH5News.setArticleUrl(articleUrl);
				mH5News.setTitle(articleTitle);
				mH5News.setId(articleId);
			}else{
				finish();
			}
		}
		reLoadPageView(mH5News);
//		from = intent.getStringExtra(Constants.FROM);
//		if (Constants.FROM_SCREEN.equals(from)) {
//			initData(intent);
//			reLoadPageView(mNews);
//		}
	}


	@Override
	public void onConnectChange() {
		isNetworkChanged = true;
		if (lay_no_net.getVisibility() == View.VISIBLE) {
			MyLog.i("wmm", "onConnectChange");
			onResume();
		}
	}
	
	@Override
	public String getUserHabitKey() {
		String key = UserCountHabit.DETAIL_PAGE_TIME;
		if(mFocusNews != null){
			key = key + mFocusNews.getId();
		}else if(mCommonNews != null){
			key = key + mCommonNews.getId();
		}else if(mH5News != null){
			key = "gdpt_"+mH5News.getId();
		}
		if(!(lastArticleId == articleId)){
			MyLog.i("wmm", "setUserCount");
			lastArticleId = articleId; 
			UserCountHabit.setUserCount(this, key, (System.currentTimeMillis() - onResume)+"");
		}
		return "";
	}

	private void openBrowser(){
		if(mNews != null){
			if(!TextUtils.isEmpty(mNews.getFromUrl())){
				Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(mNews.getFromUrl()));
				it.setAction("android.intent.action.VIEW");
				startActivity(it);
			}else if(!TextUtils.isEmpty(mNews.getArticleUrl())){
				Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(mNews.getArticleUrl()));
				it.setAction("android.intent.action.VIEW");
				startActivity(it);
			}else{
				Toast.makeText(this, getApplicationContext().getResources().getString(R.string.no_source_url), 0).show();
				return;
			}
		}else if(mH5News != null){
			Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(mH5News.getArticleUrl()));
			it.setAction("android.intent.action.VIEW");
			startActivity(it);
		}
		UserCountHabit.setUserCount(DetailPageActivity.this, UserCountHabit.DETAIL_2_BROWSER);
	}
	
	private void dismissPopup(){
		if(popup!=null && popup.isShowing()){
			popup.dismiss();
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.tv_browser:
			openBrowser();
			dismissPopup();
			break;
		case R.id.tv_refresh:
			refresh();
			dismissPopup();
			break;
		case R.id.tv_share:
			sendToFriend();
			dismissPopup();
			break;
        case R.id.copy_link:
            copyLink();
            dismissPopup();
            break;
		default:
			break;
		}
	}

    private void copyLink() {
    	try{
    		ClipboardManager clipboard =
    				(ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
    		clipboard.setText(mNews.getArticleUrl());
    		Toast.makeText(this, "复制链接成功", Toast.LENGTH_SHORT).show();
    	}catch(Exception e){
    		e.printStackTrace();
    		Toast.makeText(this, "复制链接出错了", Toast.LENGTH_SHORT).show();
    	}
    }
	@Override
	public void onBackPressed() {
		if(gameInterface != null) {
			gameInterface.onBackPress();
		} else {
			super.onBackPressed();
		}
	}

	@Override
	public void onGameExit() {
		//TODO 游戏退出时的回收处理
		gameInterface = null;
		this.finish();
	}
}
